from django.shortcuts import render
from django.http import HttpResponse
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.shortcuts import redirect
import os,subprocess,json,re
from . import models
from . import network
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

#------------------------------------------主页-----------------------------------------

#首页访问
def index(request):
    try:
        real_ip=request.META['HTTP_X_FORWARDED_FOR']
        regip = real_ip.split(",")[0]
    except:
        try:
            regip = request.META['REMOTE_ADDR']
        except:
            regip = ""
    js_t="访问主页"
    models.log.objects.create(logid=0,logname=js_t,logip=regip)
    ip_all=models.ipdb.objects.all()
    tj_all= (len(ip_all))
    ip_tj=models.ipdb.objects.filter(on_off_status=0)
    tj_on=(len(ip_tj))
    tj_off=(tj_all-tj_on)
    paginator = Paginator(ip_all, 25) # Show 25 contacts per page
    page = request.GET.get('page')
    try:
        contacts = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        contacts = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        contacts = paginator.page(paginator.num_pages)
    return render(request, 'iptmp/list.html', {'ip': contacts,'tj_all':tj_all,'tj_on':tj_on,'tj_off':tj_off})


def iplist(request):
    ip_all=models.ipdb.objects.all()
    tj_all= (len(ip_all))
    ip_tj=models.ipdb.objects.filter(on_off_status=0)
    tj_on=(len(ip_tj))
    tj_off=(tj_all-tj_on)
    paginator = Paginator(ip_all, 25) # Show 25 contacts per page
    page = request.GET.get('page')
    try:
        contacts = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        contacts = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        contacts = paginator.page(paginator.num_pages)
    return render(request, 'iptmp/iplist.html', {'ip': contacts,'tj_all':tj_all,'tj_on':tj_on,'tj_off':tj_off})




#首页查看页面
def list(request):
    ip_all=models.ipdb.objects.all()
    tj_all= (len(ip_all))
    ip_tj=models.ipdb.objects.filter(on_off_status=0)
    tj_on=(len(ip_tj))
    tj_off=(tj_all-tj_on)
    paginator = Paginator(ip_all, 25) # Show 25 contacts per page
    page = request.GET.get('page')
    try:
        contacts = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        contacts = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        contacts = paginator.page(paginator.num_pages)
    return  render(request,'iptmp/iplist.html',{'ip':contacts,'tj_all':tj_all,'tj_on':tj_on,'tj_off':tj_off})

#添加
def add(request):
    try:
        real_ip=request.META['HTTP_X_FORWARDED_FOR']
        regip = real_ip.split(",")[0]
    except:
        try:
            regip = request.META['REMOTE_ADDR']
        except:
            regip = ""
    if request.method=="POST":
        ip=request.POST['ip']
        port=request.POST['port']
        tag=request.POST['tag']
        pcname=request.POST['to_name']
        xy=request.POST['to_xy']
        ip_all=models.ipdb.objects.all()
        if len(ip.split("."))==4 and port.isdigit() and  tag: #第一级判断
            if not xy:
                xy=""
            mac=network.ip_getmac(ip)
            on_off=network.host_on_off(ip)
            # pc_name=network.ip_getname(ip)
            pc_name="没有获取"
            aa=models.ipdb.objects.filter(ip=ip)
            if aa: #判断数据库有没有此IP
                js_t="添加IP：%s失败，ip有重复"%ip
                models.log.objects.get_or_create(logid=2,logname=js_t,logip=regip)
                return  render(request,'iptmp/add.html',{'js_t':json.dumps(js_t)})
            else:#不存在返回错误
                js_t= ("成功添加IP:%s"%ip)
                aaa=models.ipdb.objects.get_or_create(ip=ip,port=port,mac=mac,ip_tag=ip.split(".")[3],tag_name=pcname,xy=xy,ip_stau=1,net_onoff=0,pc_name=pc_name,on_off_status=on_off,tag=tag)
                models.log.objects.get_or_create(logid=1,logname=js_t,logip=regip)
                return HttpResponseRedirect('/list/')
        else:
            js_t="添加IP：%s失败，输入得信息可能有误"%ip
            models.log.objects.get_or_create(logid=2,logname=js_t,logip=regip)
            return  render(request,'iptmp/add.html',{'ip':ip_all,'js_t':json.dumps(js_t)})


    ip_all=models.ipdb.objects.all()
    tj_all= (len(ip_all))
    ip_tj=models.ipdb.objects.filter(on_off_status=0)
    tj_on=(len(ip_tj))
    tj_off=(tj_all-tj_on)
    return  render(request,'iptmp/add.html',{'tj_all':tj_all,'tj_on':tj_on,'tj_off':tj_off})

#搜索页面
def find(request):
    request.encoding='utf-8'
    name =  request.GET['name'].strip()
    ip =  request.GET['ip'].strip()
    ip_all=models.ipdb.objects.all()
    tj_all= (len(ip_all))
    ip_tj=models.ipdb.objects.filter(on_off_status=0)
    tj_on=(len(ip_tj))
    tj_off=(tj_all-tj_on)
    try:
        if not ip and not name:
            return render(request,'iptmp/list.html')
        if ip and name:
            print("名字，IP一块匹配")
            ip_edit=models.ipdb.objects.filter(tag_name__icontains=name).filter(ip=ip)
            return render(request,'iptmp/list.html',{'ip':ip_edit,'tj_all':tj_all,'tj_on':tj_on,'tj_off':tj_off})
        if name:
            ip_edit=models.ipdb.objects.filter(tag_name__icontains=name)
            return render(request,"iptmp/list.html",{'ip':ip_edit,'tj_all':tj_all,'tj_on':tj_on,'tj_off':tj_off})
        if ip:
            ipn=ip.split(".")
            if len(ipn)==4:
                print("匹配全IP")
                ip_edit=models.ipdb.objects.filter(ip=ip)
                return render(request,'iptmp/list.html',{'ip':ip_edit,'tj_all':tj_all,'tj_on':tj_on,'tj_off':tj_off})
            elif len(ipn)==1:
                print("匹配单个IP")
                ip_edit=models.ipdb.objects.filter(ip_tag=ipn[0])
                return render(request,'iptmp/list.html',{'ip':ip_edit,'tj_all':tj_all,'tj_on':tj_on,'tj_off':tj_off})
    except:
        pass
    return render(request,"iptmp/list.html", )

#查看离线列表
def off(request):
    iphost=models.ipdb.objects.filter(on_off_status=1)
    ip_all=models.ipdb.objects.all()
    tj_all= (len(ip_all))
    ip_tj=models.ipdb.objects.filter(on_off_status=0)
    tj_on=(len(ip_tj))
    tj_off=(tj_all-tj_on)
    paginator = Paginator(iphost, 25) # Show 25 contacts per page
    page = request.GET.get('page')
    try:
        contacts = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        contacts = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        contacts = paginator.page(paginator.num_pages)
    return  render(request,'iptmp/list.html',{'ip':contacts,'tj_all':tj_all,'tj_on':tj_on,'tj_off':tj_off})

#查看在线列表
def on(request):
    iphost=models.ipdb.objects.filter(on_off_status=0)
    ip_all=models.ipdb.objects.all()
    tj_all= (len(ip_all))
    ip_tj=models.ipdb.objects.filter(on_off_status=0)
    tj_on=(len(ip_tj))
    tj_off=(tj_all-tj_on)
    paginator = Paginator(iphost, 25) # Show 25 contacts per page
    page = request.GET.get('page')
    try:
        contacts = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        contacts = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        contacts = paginator.page(paginator.num_pages)
    return  render(request,'iptmp/list.html',{'ip':contacts,'tj_all':tj_all,'tj_on':tj_on,'tj_off':tj_off})



#------------------------------------------维护操作-----------------------------------------


#编辑
def edit(request):
    try:
        real_ip=request.META['HTTP_X_FORWARDED_FOR']
        regip = real_ip.split(",")[0]
    except:
        try:
            regip = request.META['REMOTE_ADDR']
        except:
            regip = ""
    if request.method=="POST":
        idd=request.GET.get('q')
        ip=request.POST['ip']
        port=request.POST['port']
        pname=request.POST['to_name']
        tag=request.POST['tag']
        xy=request.POST['xy']
        if len(ip.split("."))==4 and port.isdigit() and  tag:
            mac=network.ip_getmac(ip)
            on_off=network.host_on_off(ip)
            # pc_name=network.ip_getname(ip)
            pc_name="没有获取"
            try:
                aaa=models.ipdb.objects.filter(id=idd).update(ip=ip,port=port,mac=mac,ip_tag=ip.split(".")[3],xy=xy,tag_name=pname,ip_stau=1,pc_name=pc_name,on_off_status=on_off,tag=tag)
                js_t= ("编辑IP:%s成功"%ip)
                models.log.objects.get_or_create(logid=1,logname=js_t,logip=regip)
                return HttpResponseRedirect('/list/')
            except:
                js_t="编辑失败，IP有重复"
                models.log.objects.get_or_create(logid=2,logname=js_t,logip=regip)
                return  render(request,'iptmp/list.html',{'js_t':json.dumps(js_t)})
        else:
            js_t="添加失败，输入得信息可能有误，请核对"
            models.log.objects.get_or_create(logid=2,logname=js_t,logip=regip)
            return  render(request,'iptmp/iptmp/add.html',{'js_t':json.dumps(js_t)})
    else:
        request.encoding='utf-8'
        idd=request.GET.get('q')
        try:
            ip_edit=models.ipdb.objects.filter(id=idd)
            ip_all=models.ipdb.objects.all()
            tj_all= (len(ip_all))
            ip_tj=models.ipdb.objects.filter(on_off_status=0)
            tj_on=(len(ip_tj))
            tj_off=(tj_all-tj_on)
            return  render(request,'iptmp/edit.html',{'edit_ip':ip_edit[0],'tj_all':tj_all,'tj_on':tj_on,'tj_off':tj_off})
        except:
            js_t="没有主机"
            models.log.objects.get_or_create(logid=2,logname=js_t,logip=regip)
            return render(request,'iptmp/edit.html',{'edit_ip':js_t})

#更新是否支持唤醒
def update_on_off_net(request):
    try:
        real_ip=request.META['HTTP_X_FORWARDED_FOR']
        regip = real_ip.split(",")[0]
    except:
        try:
            regip = request.META['REMOTE_ADDR']
        except:
            regip = ""
    js_t="更新一个主机在线情况"
    models.log.objects.create(logid=1,logname=js_t,logip=regip)
    if request.method=="POST":
        ip=request.POST['ip']
        tagg=request.POST['tag']
        models.ipdb.objects.filter(ip=ip).update(net_onoff=tagg)
        return HttpResponseRedirect('/list/')
    return HttpResponseRedirect('/list/')

#关闭一个主机
def shut_one(request):
    if request.method=="POST":
        ipone=request.POST['ip']
        iip=models.ipdb.objects.get(ip=ipone)
        print('关闭',iip.ip)
        try:
            # stau=subprocess.check_output("shutdown -s  -t 60 -c '电脑将在3分钟后关机，请立刻保存资料' -m \\\%s"%iip.ip).decode("GBK")
            stau=os.system("shutdown -s  -t 60 -c '电脑将在3分钟后关机，请立刻保存资料' -m \\\%s"%iip.ip)
            js_t="关闭成功"
            ip_all=models.ipdb.objects.all()
            return  render(request,'iptmp/list.html',{'ip':ip_all,'jstk':json.dumps(js_t)})
        except:
            print(js_t)
            url=request.POST['urlpath']
            return HttpResponseRedirect(url)
    ip=models.ipdb.objects.all()
    return  render(request,'iptmp/list.html',{'ip':ip})

#重启 一个主机
def reboot_one(request):
    if request.method=="POST":
        ipone=request.POST['ip']
        print ("重启主机",ipone)
        iip=models.ipdb.objects.get(ip=ipone)
        try:
            subprocess.check_output("shutdown -r  -t 60 -c '电脑将在3分钟后重启，请立刻保存资料' -m \\\%s"%iip.ip).decode("GBK")
        except:
            pass
        js_t="重启成功"
        print(js_t)
        url=request.POST['urlpath']
        return HttpResponseRedirect(url)
    ip=models.ipdb.objects.all()
    return  render(request,'iptmp/list.html',{'ip':ip})

#取消一个关机
def noshut_one(request):
    if request.method=="POST":
        ipone=request.POST['ip']
        iip=models.ipdb.objects.get(ip=ipone)
        print ("取消主机",ipone)
        try:
            subprocess.check_output("shutdown -a -m \\\%s"%iip.ip).decode("GBK")
        except:
            pass
        js_t="取消成功"
        print(js_t)
        url=request.POST['urlpath']
        return HttpResponseRedirect(url)
    ip=models.ipdb.objects.all()
    return  render(request,'iptmp/list.html',{'ip':ip})

#唤醒一个主机
def net_one(request):
    if request.method=="POST":
        subprocess.check_output('netsh interface set interface "外网" disabled').decode("GBK")
        ipt=request.POST['ip']
        url=request.POST['urlpath']
        print("开始唤醒主机",ipt)
        ipone=models.ipdb.objects.get(ip=ipt)
        print(ipone.mac)
        network.netall(ipone.mac)
        js_t="唤醒成功"
        ip_all=models.ipdb.objects.all()
        subprocess.check_output('netsh interface set interface "外网" enabled').decode("GBK")
        print (url)
        return HttpResponseRedirect(url)
    ip=models.ipdb.objects.all()
    return HttpResponseRedirect('/list/')

#删除某一条数据
def ip_del(request):
    if request.method=="POST":
        iip=request.POST['ip_bat']
        obj=models.ipdb.objects.get(id=iip).delete()
        return HttpResponseRedirect('/list/')
    ip=models.ipdb.objects.all()
    return HttpResponseRedirect('/list/')


def log(request):
    logg=models.log.objects.all().order_by('-createtime')
    paginator = Paginator(logg, 50) # Show 25 contacts per page
    page = request.GET.get('page')
    try:
        contacts = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        contacts = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        contacts = paginator.page(paginator.num_pages)
    return render(request,"iptmp/log.html",{'logg':contacts})




#------------------------------------------高级页面-----------------------------------------
def gao(request):
    pcall=models.pc_config.objects.all()
    ip_all=models.ipdb.objects.all()
    tj_all= (len(ip_all))
    ip_tj=models.ipdb.objects.filter(on_off_status=0)
    tj_on=(len(ip_tj))
    tj_off=(tj_all-tj_on)
    return render(request, 'iptmp/gaoji.html', {'pc_config': pcall,'tj_all':tj_all,'tj_on':tj_on,'tj_off':tj_off})


#上传模板导入
def importxls(request):
    if request.method == "POST":    # 请求方法为POST时，进行处理
        myFile =request.FILES.get("fafafa", None)    # 获取上传的文件，如果没有文件，则默认为None
        if not myFile:
            js_t="没有选择文件，请选择"
            return render(request,'iptmp/list.html',{'js_t':json.dumps(js_t)})
        filename=os.path.join("tp/static/upload/",myFile.name)
        if filename.split(".")[1]!="xls":
            js_t="不是xls文件，请重新输入"
            return render(request,'iptmp/list.html',{'js_t':json.dumps(js_t)})
        destination = open(filename,'wb+')    # 打开特定的文件进行二进制的写操作
        for chunk in myFile.chunks():      # 分块写入文件
            destination.write(chunk)
        destination.close()
        print("上传成功------------")
        xlspath=os.path.join("tp/static/upload/",myFile.name)
        xls_data=network.readxls(xlspath)

        for cc in xls_data:
            print(cc)
            lisa=cc[0].split(":")
            if len(lisa)==1:
                port=3389
            elif len(lisa)==2:
                port=cc[0].split(":"[1])
                print (cc[0])
                print (cc[1])
                print (int(cc[2]))
                print (cc[3])
                print("---------")
            models.ipdb.objects.get_or_create(ip=cc[0],port=port,mac="none",ip_tag=0,tag_name=cc[1],xy=str(cc[3]),ip_stau=1,pc_name="none",net_onoff=0,on_off_status=1,tag=cc[2])
        return HttpResponseRedirect('/list/')
    return HttpResponseRedirect('/list/')

#删除所有记录
def delall(request):
    ipall=models.ipdb.objects.all().delete()
    return HttpResponseRedirect("/list/")

#更新mac地址
def update_mac(request):
    js_t=network.update_mac()
    return render(request,'iptmp/gaoji.html',{'js_t':json.dumps(js_t)})

#更新主机名字
def update_pcname(request):
    js_t=network.update_pcname()
    return render(request,'iptmp/gaoji.html',{'js_t':json.dumps(js_t)})

#更新在线情况
def update_on_off(request):
    print("开始更新在线情况")
    js_t=network.all_if_pc_off()
    return render(request,'iptmp/gaoji.html',{'js_t':json.dumps(js_t)})


# 关闭所有主机
def all_shutdown(request):
    mac=models.ipdb.objects.all().values()
    for i in mac:
        try:
            subprocess.check_output("shutdown -s -t 180 -c '电脑即将关闭，请立刻保存资料' -m \\\%s"%i['ip']).decode("GBK")
        except:
            continue
    return HttpResponseRedirect('/gao/')

# 取消关闭所有主机
def all_noshutdown(request):
    mac=models.ipdb.objects.all().values()
    print ("开始循环所有主机")
    for i in mac:
        print ("主机",i)
        try:
            subprocess.check_output("shutdown -a  -m \\\%s"%i['ip']).decode("GBK")
        except:
            continue
    return HttpResponseRedirect('/gao/')

#唤醒全部主机
def all_net(request):
    mac=models.ipdb.objects.all().values()
    for i in mac:
        print (i['mac'])
        network.netall(i['mac'])
    return HttpResponseRedirect('/gao/')



#更新所有
def update_all(request):
    network.update_mac()
    network.update_pcname()
    network.all_if_pc_off()
    js_t="操作成功"
    return render(request,'iptmp/gaoji.html',{'js_t':json.dumps(js_t)})




#------------------------------------------维护为题提交-----------------------------------------


def pcwh(request):
    if request.method=="POST":
        ip=request.POST['ip']
        wt=request.POST['wt']
        jjff=request.POST['jjff']
        fkr=request.POST['fkr']
        tag=request.POST['tag']
        print (ip,wt)
        models.pc_wh.objects.create(wh_ip=ip,wh_id=1,wh_ren=fkr,wh_name=wt,wh_text=wt,wh_xf_text=jjff,wh_yes_no=tag)
        return HttpResponseRedirect('/pcwh/')
    whall=models.pc_wh.objects.all()
    ip_all=models.ipdb.objects.all()
    tj_all= (len(ip_all))
    ip_tj=models.ipdb.objects.filter(on_off_status=0)
    tj_on=(len(ip_tj))
    tj_off=(tj_all-tj_on)
    return render(request, 'iptmp/pc_wh.html', {'wh': whall,'tj_all':tj_all,'tj_on':tj_on,'tj_off':tj_off})

def pcwh_tj(request):
    if request.method=="POST":
        tag=request.POST['tag']
        id=request.POST['id']
        print (tag,id)
        models.pc_wh.objects.filter(id=id).update(wh_yes_no=tag)
        return HttpResponseRedirect('/pcwh/')
    whall=models.pc_wh.objects.all()
    return render(request,'iptmp/pc_wh.html',{'wh':whall})



#------------------------------------------主机配置-----------------------------------------


def pc_config(request):
    if request.method=="POST":
        tag=request.POST['tag']
        id=request.POST['id']
        print (tag,id)
        models.pc_wh.objects.filter(id=id).update(wh_yes_no=tag)
        return HttpResponseRedirect('/pcwh/')
    pcall=models.pc_config.objects.all()
    ip_all=models.ipdb.objects.all()
    tj_all= (len(ip_all))
    ip_tj=models.ipdb.objects.filter(on_off_status=0)
    tj_on=(len(ip_tj))
    tj_off=(tj_all-tj_on)
    return render(request, 'iptmp/pc_config.html', {'pc_config': pcall,'tj_all':tj_all,'tj_on':tj_on,'tj_off':tj_off})






